using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;

namespace IWS.Lib.SingleSignOn
{
	public class MediumTrustSecurity
	{
		/// <summary>
		/// Writes a key to a keyfile. 
		/// </summary>
		/// <param name="path"></param>
		/// <param name="key"></param>
		public static void WriteKeyFile(string path, string key)
		{
			//Create the XmlDocument.
			XmlDocument doc = new XmlDocument();
			doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-16", null));
			XmlElement root = doc.CreateElement("KeyFile");
			doc.AppendChild(root);
			XmlElement ekey = doc.CreateElement("Key");
			XmlCDataSection keysection = doc.CreateCDataSection(key);
			root.AppendChild(ekey);
			ekey.AppendChild(keysection);
			using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
			{
				doc.Save(fs);
				fs.Flush();
				fs.Close();
			}

			//System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			//doc.LoadXml("<?xml version=\"1.0\" encoding=\"unicodeFFFE\" ?><KeyFile><Key>" + key + "</Key></KeyFile>");
		}
		/// <summary>
		/// Returns the key inside a key file. 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static string ReadKeyFile(string path)
		{
			string key = string.Empty;
			try
			{
				XmlDocument doc = new XmlDocument();
				using (System.IO.FileStream fs = new System.IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
				{
					doc.Load(fs);
					fs.Close();
				}

				key = doc.ChildNodes[1].FirstChild.InnerText;
			}
			catch (IOException ex)
			{
				throw new ApplicationException("Cannot read local key file.\r\n" + ex.Message, ex);
			}
			catch (ArgumentNullException ex)
			{
				throw new ApplicationException("No keyfile name was supplied.\r\n" + ex.Message, ex);
			}
			return key;
		}

		public static string ResolveKeyFile(string filename)
		{
			if (filename != null)
			{
				if (filename.StartsWith("@"))
				{
					filename = Path.Combine(Application.StartupPath.TrimEnd(new char[] { Path.DirectorySeparatorChar }), filename.Replace("@", ""));
				}
				else if (filename.StartsWith("~/"))
				{
					//try to use the HTTPCOntext first
					if (System.Web.HttpContext.Current != null)
						filename = System.Web.HttpContext.Current.Server.MapPath(filename);
					else
					{
						//find the bin. then 
						System.Reflection.Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();
						Uri uri = new Uri(ass.CodeBase);
						string root = Path.GetDirectoryName(Path.GetDirectoryName(uri.AbsolutePath));
						filename = string.Format("{0}\\{1}", root, filename.Replace("~/", ""));
					}
				}
			}
			return filename;
		}
	}
}
